﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Dependency Injection</title>
<link type="text/css" rel="stylesheet" href="bootstrap.min.css" />
</head>

<body>

<ul>
	<li><a href="#DocWhatIsDI">What is Dependency Injection</a>
	<ul>
		<li><a href="#DocProblems">Problems of traditional way</a></li>
		<li><a href="#DocSolutions">Solution</a><ul>
			<li><a href="#DocConstructorInjection">Constructor injection</a></li>
			<li><a href="#DocPropertyInjection">Property injection</a></li>
		</ul>
		</li>
		<li><a href="#DocDIFrameworks">Dependency Injection frameworks</a></li>
	</ul>
	</li>
	<li><a href="#DocAbpInfrastructure">ASP.NET Boilerplate Dependency Injection infrastructure</a><ul>
		<li><a href="#DocRegisterDependencies">Registering</a><ul>
			<li><a href="#DocConventionalRegister">Conventional registrations</a></li>
			<li><a href="#DocHelperInterfaces">Helper interfaces</a></li>
			<li><a href="#DocCustomRegistration">Custom/Direct registration</a></li>
		</ul>
		</li>
		<li><a href="#DocResolvingDependencies">Resolving</a><ul>
			<li><a href="#DocResolveConstAndProp">Constructor &amp; Property Injection</a></li>
			<li><a href="#DocIocHelper">IIocResolver and IIocManager</a></li>
		</ul>
		</li>
		<li><a href="#DocExtras">Extras</a><ul>
			<li><a href="#DocIShouldInitialize">IShouldInitialize interface</a></li>
		</ul>
		</li>
		<li><a href="#DocMvcAndWebApiIntegration">ASP.NET MVC &amp; ASP.NET Web API integration</a></li>
		<li><a href="#DocLastNotes">Last notes</a></li>
	</ul>
	</li>
</ul>
<h3 id="DocWhatIsDI">What is Dependency Injection</h3>
<p>If you already know Dependency Injection concept, Constructor and Property 
Injection patterns, you can skip to the <a href="#DocAbpInfrastructure">next section</a>.</p>
<p>Wikipedia says: "<em>Dependency injection is a software design pattern in which one or more dependencies (or services) are injected, or passed by reference, 
into a dependent object (or client) and are made part of the client's state. The pattern separates the creation of a client's dependencies from its own behavior,
which allows program designs to be loosely coupled and to follow the dependency inversion and single responsibility principles. It directly contrasts the
service locator pattern, which allows clients to know about the system they use to find dependencies.</em>".</p>
<p>It's very hard to manage dependencies and develop a modular and well 
structured application without using dependency injection techniques.</p>
<h4 id="DocProblems">Problems of traditional way</h4>
<p>In an application, classes depend on each other. Assume that we have an
<a href="/Pages/Documents/Application-Services">application service</a> that 
uses a <a href="/Pages/Documents/Entities">repository</a> to insert
<a href="/Pages/Documents/Entities">entities</a> to database. In this 
situation, the application service class is dependent to the repository class. 
See the example:</p>
<pre lang="cs">public class PersonAppService
{
    private IPersonRepository _personRepository;

    public PersonAppService()
    {
        _personRepository = new PersonRepository();            
    }

    public void CreatePerson(string name, int age)
    {
        var person = new Person { Name = name, Age = age };
        _personRepository.Insert(person);
    }
}
</pre>
<p><strong>PersonAppService</strong> uses <strong>PersonRepository</strong> to 
insert a <strong>Person</strong> to the database. Problems of this code:</p>
<ul>
	<li>PersonAppService uses <strong>IPersonRepository</strong> reference in
	<strong>CreatePerson</strong> method, so this method depends on 
	IPersonRepository, instead of PersonRepository concrete class. But the 
	PersonAppService still depends on PersonRepository in it's constructor. 
	Components should depend on interfaces rather than implementation. This is 
	known as Dependency Inversion principle. </li>
	<li>If the PersonAppService creates the PersonRepository itself, it become 
	dependent to a specific implementation of IPersonRepository interface and 
	can not work with another implementation. Thus, separating interface from 
	implementation becomes meaningless. Hard-dependencies makes code base 
	tightly coupled and low re-usable.</li>
	<li>We may need to change creation of PersonRepository in the future. Say, 
	we may want to make it singleton (single shared instance rather than 
	creating an object for each usage). Or we may want to create more than one 
	class those implement IPersonRepository and we want to create one of them 
	conditionally. In this situation, we should change all classes that depends 
	on IPersonRepository.</li>
	<li>With such a dependency, it's very hard (or impossible) to unit test the 
	PersonAppService.</li>
</ul>
<p>To overcome some of these problems, factory pattern can be used. Thus, creation 
of repository class is abstracted. See the code below:</p>
<pre lang="cs">public class PersonAppService
{
    private IPersonRepository _personRepository;

    public PersonAppService()
    {
        _personRepository = PersonRepositoryFactory.Create();            
    }

    public void CreatePerson(string name, int age)
    {
        var person = new Person { Name = name, Age = age };
        _personRepository.Insert(person);
    }
}
</pre>

<p>PersonRepositoryFactory is a static class that creates and returns an 
IPersonRepository. This is known as <strong>Service Locator</strong> pattern. Creation problems are solved since PersonAppService does not 
know how to create an implementation of IPersonRepository and it's independent 
from PersonRepository implementation. But,still there are some problems:</p>
<ul>
	<li>In this time, PersonAppService depends on PersonRepositoryFactory. This 
	is more acceptable but still there is a hard-dependency.</li>
	<li>It's tedious to write a factory class/method for each repository or for 
	each dependency.</li>
	<li>It's not well testable again, since it's hard to make PersonAppService 
	to use some mock implementation of IPersonRepository.</li>
</ul>
<h4 id="DocSolution">Solution</h4>
<p>There are some best practices (patterns) to depend on other classes.</p>
<h4 id="DocConstructorInjection">Constructor Injection pattern</h4>
<p>The example above can be re-written as shown below:</p>
<pre lang="cs">public class PersonAppService
{
    private IPersonRepository _personRepository;

    public PersonAppService(IPersonRepository personRepository)
    {
        _personRepository = personRepository;
    }

    public void CreatePerson(string name, int age)
    {
        var person = new Person { Name = name, Age = age };
        _personRepository.Insert(person);
    }
}
</pre>

<p>This is known as <strong>constructor injection</strong>. Now, 
PersonAppService does not know which classes implement IPersonRepository and how 
to create it. Who needs to use PersonAppService, first creates an 
IPersonRepository and pass it to constructor of PersonAppService as shown below:</p>
<pre lang="cs">var repository = new PersonRepository();
var personService = new PersonAppService(repository);
personService.CreatePerson("Yunus Emre", 19);</pre>
<p>Constructor Injection is a perfect way of making a class independent to 
creation of dependent objects. But, there are some problems with the code above:</p>
<ul>
	<li>Creating a PersonAppService become harder. Think that it has 4 
	dependency, we must create these 4 dependent object and pass them into the 
	constructor of the PersonAppService.</li>
	<li>Dependent classes may have other dependencies (Here, PersonRepository 
	may has dependencies). So, we must create all dependencies of 
	PersonAppService, all dependencies of dependencies and so on.. In that way, 
	we may not even create a single object since dependency graph is too 
	complex.</li>
</ul>
<p>Fortunately, there are <a href="#DocDIFrameworks">Dependency Injection 
frameworks</a> automates to manage dependencies.</p>
<h4 id="DocPropertyInjection">Property Injection pattern</h4>
<p>Constructor injection pattern is a perfect way of providing dependencies of a 
class. In this way, you can not create an instance of the class without 
supplying dependencies. It's also a strong way of explicitly declaring what's 
the requirements of the class to properly work.</p>
<p>But, in some situations, the class depends on another class but also can work 
without it. This is usually true for cross-cutting concerns such as logging. A 
class can work without logging, but it can write logs if you supply a logger. In 
this case, you can define dependencies as public properties rather than getting 
them in constructor. Think that we want to write logs in PersonAppService. We 
can re-write the class as like below:</p>
<pre lang="cs">public class PersonAppService
{
    public ILogger Logger { get; set; }

    private IPersonRepository _personRepository;

    public PersonAppService(IPersonRepository personRepository)
    {
        _personRepository = personRepository;
        Logger = NullLogger.Instance;
    }

    public void CreatePerson(string name, int age)
    {
        Logger.Debug("Inserting a new person to database with name = " + name);
        var person = new Person { Name = name, Age = age };
        _personRepository.Insert(person);
        Logger.Debug("Successfully inserted!");
    }
}</pre>
<p>NullLogger.Instance is a singleton object that implements ILogger but 
actually does nothing (does not write logs. It implements ILogger with empty 
method bodies). So, now, PersonAppService can write logs if you set Logger after 
creating the PersonAppService object like below:</p>
<pre lang="cs">var personService = new PersonAppService(new PersonRepository());
personService.Logger = new Log4NetLogger();
personService.CreatePerson("Yunus Emre", 19);</pre>
<p>Assume that Log4NetLogger implements ILogger and write logs using Log4Net 
library. Thus, PersonAppService can actually write logs. If we do not set 
Logger, it does not write logs. So, we can say the ILogger is an <strong>
optional dependency </strong>of PersonAppService.</p>

<p>Almost all of Dependency Injection frameworks support Property Injection 
pattern.</p>
<h4 id="DocDIFrameworks">Dependency Injection frameworks</h4>
<p>There are many dependency injection framework that automates resolving 
dependencies. They can create objects with all dependencies (and dependencies of 
dependencies recursively). So, you just write your class with constructor &amp; 
property injection patterns, DI framework handles the rest! In a good 
application, your classes are independent even from DI framework. There will be 
a few lines of code or classes that explicitly interact with DI framework in 
your whole application.</p>
<p>ASP.NET Boilerplate uses <a href="http://docs.castleproject.org/Default.aspx?Page=MainPage">Castle 
Windsor</a>  framework for Dependency Injection. It's one of the most mature DI 
frameworks. There are many other frameworks like Unity, Ninject, StructureMap, 
Autofac and so on.</p>
<p>In a dependency injection framework, you first register your 
interfaces/classes to the dependency injection framework, then you can resolve 
(create) an object. In Castle Windsor, 
it's something like that:</p>
<pre>var container = new WindsorContainer();

container.Register(
        Component.For&lt;IPersonRepository&gt;().ImplementedBy&lt;PersonRepository&gt;().LifestyleTransient(),
        Component.For&lt;IPersonAppService&gt;().ImplementedBy&lt;PersonAppService&gt;().LifestyleTransient()
    );

var personService = container.Resolve&lt;IPersonAppService&gt;();
personService.CreatePerson(&quot;Yunus Emre&quot;, 19);</pre>
<p>We first created the <strong>WindsorContainer</strong>. then <strong>
registered </strong>PersonRepository and PersonAppService with their interfaces. 
Then we asked to container to create an IPersonAppService. It created 
PersonAppService with dependencies and returned back. Maybe it's not so clear of 
advantage of using a DI framework in this simple example, but think you will 
have many classes and dependencies in a real enterprise application. Surely, 
registering dependencies will be somewhere else from creation and using objects 
and made only one time in an application startup.</p>
<p>Notice that we also declared <strong>life cycle </strong>of objects as
<strong>transient</strong>. That means whenever we resolves an object of these 
types, a new instance will be created. There are many different life cycles 
(like <strong>singletion</strong>).</p>
<h3 id="DocAbpInfrastructure">ASP.NET Boilerplate Dependency Injection infrastructure</h3>
<p>ASP.NET Boilerplate almost makes invisible of using the dependency injection 
framework when you write your application by following best practices and some 
conventions.</p>
<h4 id="DocRegisterDependencies">Registering</h4>
<p>There are different ways of registering your classes to Dependency Injection 
system in ASP.NET Boilerplate. Most of time, conventional registration will be 
sufficient.</p>
<h4 id="DocConventionalRegister">Conventional registrations</h4>

<p>ASP.NET Boilerplate automatically registers all
<a href="/Pages/Documents/Repositories">Repositories</a>, 
<a href="/Pages/Documents/Domain-Services">Domain Services</a>,
<a href="/Pages/Documents/Application-Services">Application Services</a>, MVC 
Controllers and Web API Controllers 
by 
convention. For example, you may have a IPersonAppService interface and a PersonAppService 
class that implements it:</p>
<pre>public interface IPersonAppService : IApplicationService
{
    //...
}

public class PersonAppService : IPersonAppService
{
    //...
}</pre>
<p>ASP.NET Boilerplate automatically registers it since it implements <strong>
IApplicationService </strong>interface (It's just an empty interface). It's 
registered as <strong>transient </strong>(created instance per usage). When you 
inject (using constructor injection) IPersonAppService interface to a class, a 
PersonAppService object is created and passed into constructor automatically. </p>
<p><strong>Naming conventions </strong>are very important here. For example you 
can change name of PersonAppService to MyPersonAppService or another name which 
contains 'PersonAppService' postfix since the IPersonAppService has this 
postfix. But you can not name your service as PeopleService. If you do it, it's 
not registered for IPersonAppService automatically (It's registered to DI 
framework but with self-registration, not with interface), so, you should manually 
register it if you want.</p>
<p>ASP.NET Boilerplate registers assemblies by convention. So, you should tell 
to ASP.NET Boilerplate to register your assembly by convention. It's pretty 
easy:</p>
<pre lang="cs">IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());</pre>
<p>Assembly.GetExecutingAssembly() gets a reference to the assembly which 
contains this code. You can pass other assemblies to 
RegisterAssemblyByConvention method. This is generally done when your module is 
being initialized. See ASP.NET Boilerplate's
<a href="/Pages/Documents/Module-System">module system</a> for more.</p>
<p>You can write your own conventional registration class by implementing
<strong>IConventionalRegisterer</strong> interface and calling <strong>IocManager.AddConventionalRegisterer</strong> 
method with your class. You should add it in pre-initialize method of your 
module.</p>
<h4 id="DocHelperInterfaces">Helper Interfaces</h4>
<p>You may want to register a specific class that does not fit to conventional 
registration rules. ASP.NET Boilerplate provides <strong>ITransientDependency</strong> and 
<strong>ISingletonDependency</strong> interfaces as a shortcut. For example:</p>
<pre lang="cs">public interface IPersonManager
{
<span lang="tr">    //...</span>
}

public class MyPersonManager : IPersonManager, ISingletonDependency
{
    <span lang="tr">//...</span>
}</pre>
<p>In that way, you can easily register MyPersonManager. When need 
to inject a IPersonManager, MyPersonManager class is used. Notice that dependency is 
declared as <strong>Singleton</strong>. Thus, a single instance of 
MyPersonManager is created and same object is passed to all needed classes. It's 
just created in first usage, then same instance is used in whole life of the 
application.</p>

<h4 id="DocCustomRegistration">Custom/Direct registration</h4>
<p>If the approaches described before is no sufficient for your situation, you 
can direcly use <strong>Castle Windsor</strong> to register your classes and dependencies. Thus, 
you will have all capabilities of registering in Castle Windsor.</p>
<p>Castle Windsor has <strong>IWindsorInstaller</strong> interface that can be 
implemented for registration. You can create a class that implements IWindsorInstaller 
interface in your application:</p>
<pre lang="cs">public class MyInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly().BasedOn&lt;IMySpecialInterface&gt;().LifestylePerThread().WithServiceSelf());
    }
}</pre>ASP.NET Boilerplate automatically finds and executes this class. Lastly, you 
can reach to the WindsorContainer using <strong>IIocManager.IocContainer</strong> 
property. For more information, read
<a href="http://docs.castleproject.org/Default.aspx?Page=MainPage">Windsor's 
documentation</a>&nbsp;<h4 id="DocResolvingDependencies">Resolving</h4>
<p>Registration informs IOC (Inversion of Control) Container (a.k.a. DI 
frameowk) about your classes, their dependencies and lifecycles. Somewhere in 
your application you need to create objects using IOC Container. ASP.NET 
Provides a few options for resolving dependencies.</p>
<h4 id="DocResolveConstAndProp">Constructor &amp; Property Injection</h4>
<p>You can use constructor and property injection to get dependencies to your 
classes as <strong>best practice</strong>. You should do it that way wherever 
it's possible. An example:</p>
<pre lang="cs">public class PersonAppService
{
    public ILogger Logger { get; set; }

    private IPersonRepository _personRepository;

    public PersonAppService(IPersonRepository personRepository)
    {
        _personRepository = personRepository;
        Logger = NullLogger.Instance;
    }

    public void CreatePerson(string name, int age)
    {
        Logger.Debug("Inserting a new person to database with name = " + name);
        var person = new Person { Name = name, Age = age };
        _personRepository.Insert(person);
        Logger.Debug("Successfully inserted!");
    }
}</pre>
<p>IPersonRepository is injected from constructor and ILogger is injected with 
public property. In that way, your code will be unaware of dependency injection 
system at all. This is the most proper way of using DI system.</p>
<h4 id="DocIocHelper">IIocResolver and IIocManager</h4>
<p>Sometime you may have to directly resolve your dependency instead of 
constructor &amp; property injection. This should be avoided when possible, but it 
may be impossible. ASP.NET Boilerplate provides some services those can be injected 
and used easily. Example:</p>
<pre lang="cs">public class MySampleClass : ITransientDependency
{
    private readonly IIocResolver _iocResolver;

    public MySampleClass(IIocResolver iocResolver)
    {
        _iocResolver = iocResolver;
    }

    public void DoIt()
    {
        //Resolving, using and releasing manually
        var personService1 = _iocResolver.Resolve&lt;PersonAppService&gt;();
        personService1.CreatePerson(new CreatePersonInput { Name = &quot;Yunus&quot;, Surname = &quot;Emre&quot; });
        _iocResolver.Release(personService1);

        //Resolving and using in a safe way
        using (var personService2 = _iocResolver.ResolveAsDisposable&lt;PersonAppService&gt;())
        {
            personService2.Object.CreatePerson(new CreatePersonInput { Name = &quot;Yunus&quot;, Surname = &quot;Emre&quot; });
        }
    }
}</pre>
<p>MySampleClass in an example class in an application. It constructor-injected
<strong>IIcResolver</strong> and used it to resolve and release objects. There 
are a few overloads of <strong>Resolve</strong> method can be used as needed.<strong> Release </strong>method is used to 
release component (object). It's <strong>critical </strong>
to call Release if you're manually resolving an object. Otherwise, your 
application has some memory leak problem. To be sure of releasing the object, 
use <strong>ResolveAsDisposable</strong> (as shown in the example above) 
wherever it's possible. It automatically calls Release at the end of the using block.</p>
<p>If you want to directly reach to IOC Container (Castle Windsor) to resolve dependencies, you 
can consturctor-inject <strong>IIocManager</strong> and use <strong>IIocManager.IocContainer</strong> 
property. If you are in a static context or can not inject IIocManager, as a 
last chance, you can use singleton object <strong>IocManager.Instance</strong> 
everywhere. But, in that case your codes will not be easy to test.</p>
<h4>Extras</h4>
<h5>IShouldInitialize interface</h5>
<p>Some classes need to be initialized before first usage. IShouldInitialize has 
an Initialize() method. If you implement it, then your Initialize() method is 
automatically called just after creating your object (before used). Surely, you 
should inject/resolve the object in order to work this feature.</p>

<h4 id="DocMvcAndWebApiIntegration">ASP.NET MVC &amp; ASP.NET Web API integration</h4>
<p>Surely, we must call dependency injection system to resolve the root object 
in dependency graph. In an <strong>ASP.NET MVC </strong>application, it's 
generally a <strong>Controller </strong>class. We can use contructor injection and property injection
patterns also in controllers. When a request come to our application, the 
controller is created using IOC container and all dependencies are resolved 
recursively. So, who does that? It's done automatically by ASP.NET Boilerplate 
by extending ASP.NET MVC's default controller factory. As similar, it's true for 
ASP.NET Web API also. You don't care about creating and disposing objects.</p>

<h4>Last notes</h4>
<p>ASP.NET Boilerplate simplifies and automates using dependency injection as 
long as you follow the rules and use the structures above. Most of times you 
will not need more. But if you need, you can directly use all power of Castle 
Windsor to perform any task (like custom registrations, injection hooks, 
interceptors and so on).</p>

</body>

</html>
